/*
 * @Date         : 2022-11-09 16:33:37
 * @LastEditTime : 2022-11-18 15:53:42
 * @Author       : wenglong
 * @LastEditors  : wenglong
 * @Description  : 广告投放转化人群弹窗的动态化表单
 */
import { useEffect, useState } from 'react';
import { useDebounce } from '@cfe/hooks';
import {
  Checkbox,
  DatePicker,
  Divider,
  Form,
  InputNumber,
  Radio,
  Select,
  Spin,
} from 'antd';

import request from '@/utils/request';
import { afterDay, pastDay } from '@/utils/time';

import {
  DIMENSION_TYPE_LIST,
  DIMENSION_TYPE_MAP,
  MEASURE_TYPE_LIST,
} from '../constants';

import BatchUpload from './BatchUpload';

const { RangePicker } = DatePicker;

// 大于一年或者小于一年都禁止
const disabledDate = (current) =>
  current && (current < pastDay(365) || current > afterDay(365));

const AdTransformPeople = (props) => {
  const { form } = props;
  const [dimensionId, setDimensionId] = useState('campaign');
  const [fetching, setFetching] = useState(false);
  const [selectedTag, setSelectedTag] = useState([]);
  const [isAllSelected, setIsAllSelected] = useState(false);
  const [options, setOptions] = useState([]);

  const handleSearchText = useDebounce((keyword = '') => {
    setIsAllSelected(false);
    setFetching(true);
    // 后端设计,勿动
    request(`/api/dmp/tag/dim_list/${dimensionId}?keyword=${keyword}`, {
      method: 'post',
      data: {},
    }).then((resp) => {
      setFetching(false);
      setOptions(
        resp.data.map((item) => ({
          label: item.name,
          value: item.id,
        })),
      );
    });
  }, 300);

  const handleChange = (values) => {
    setSelectedTag(values);
    // 手动设置否则不更新页面,勿删
    form.setFieldValue('dimensionValue', values);
  };

  useEffect(() => {
    handleSearchText();
  }, [dimensionId]);

  return (
    <Form form={form}>
      <Form.Item
        label="广告创意"
        rules={[{ required: true }]}
        name="dimensionType"
        initialValue={1}
      >
        <Radio.Group
          onChange={(e) => {
            setDimensionId(e.target.dimensionType);
            handleChange([]);
          }}
        >
          {DIMENSION_TYPE_LIST.map((item) => (
            <Radio
              key={item.value}
              value={item.value}
              dimensionType={item.name}
            >
              {item.label}
            </Radio>
          ))}
        </Radio.Group>
      </Form.Item>
      <Form.Item
        label={DIMENSION_TYPE_MAP[dimensionId]}
        rules={[{ required: true }]}
        name="dimensionValue"
      >
        <Select
          labelInValue={true}
          placeholder={`请筛选${DIMENSION_TYPE_MAP[dimensionId]}`}
          maxTagTextLength={5}
          options={options}
          mode="multiple"
          notFoundContent={fetching ? <Spin size="small" /> : null}
          value={selectedTag}
          onSearch={handleSearchText}
          style={{ width: 400 }}
          filterOption={false}
          maxTagCount="responsive"
          onChange={handleChange}
          dropdownRender={(allSelectValue) => (
            <div>
              <div style={{ padding: '4px 8px 8px 8px', cursor: 'pointer' }}>
                <Checkbox
                  checked={isAllSelected}
                  onChange={(e) => {
                    if (e.target.checked === true) {
                      setIsAllSelected(true);
                      handleChange(selectedTag.concat(options));
                    } else {
                      setIsAllSelected(false);
                      handleChange([]);
                    }
                  }}
                >
                  全选
                </Checkbox>
              </div>
              <Divider style={{ margin: '0' }} />
              {/* Option 标签值 */}
              {allSelectValue}
            </div>
          )}
        />
      </Form.Item>
      <BatchUpload
        onChange={handleChange}
        setSelectState={setIsAllSelected}
        url="/api/dmp/tag/ad/multiple_search"
        requestData={{
          id_type: dimensionId,
        }}
        textAreaProps={{
          placeholder: '支持批量上传计划、单元、创意id(非名称),用回车分隔',
        }}
        style={{
          marginLeft: '60px',
          top: '-15px',
        }}
      />
      <Form.Item label="指定时间" rules={[{ required: true }]} name="dateRange">
        <RangePicker format="YYYY-MM-DD" disabledDate={disabledDate} />
      </Form.Item>
      <Form.Item
        label="核心行为"
        rules={[{ required: true }]}
        name="measureType"
      >
        <Select
          placeholder="请选择核心行为"
          optionFilterProp="children"
          options={MEASURE_TYPE_LIST}
        />
      </Form.Item>
      <Form.Item
        style={{ display: 'inline-block' }}
        label="互动次数"
        rules={[{ required: true }]}
        name="measureValueRangeStart"
      >
        <InputNumber min={1} max={10000} />
      </Form.Item>
      <span
        style={{
          display: 'inline-flex',
          height: 33,
          lineHeight: '33px',
          margin: '0px 10px',
        }}
      >
        至
      </span>
      <Form.Item
        style={{ display: 'inline-block' }}
        rules={[{ required: true }]}
        name="measureValueRangeEnd"
      >
        <InputNumber min={1} max={10000} />
      </Form.Item>
      <span
        style={{
          color: '#a9a9a9',
          display: 'inline-flex',
          height: 33,
          lineHeight: '33px',
          margin: '0px 10px',
        }}
      >
        最大值不超过10000
      </span>
    </Form>
  );
};

export default AdTransformPeople;
